//
//  SSIDSettingsVC.swift
//  MIFI
//
//  Created by 金嗓子卡卡 on 2019/5/4.
//  Copyright © 2019 NJMifi. All rights reserved.
//

import UIKit

class SSIDSettingsVC: RootVC {
    
    private let datas = ["Network Name (SSID)*",
                         "Broadcast Network Name (SSID)",
                         "Security Mode",
                         "Password *",
                         "Maximum Number of Clients"]
    
    private var values = ["","","","",""]
    
    private lazy var nameSwitch: UISwitch = {
        let sw = UISwitch(frame: CGRect(x: 0, y: 10, width: 50, height: 30))
        sw.right = screenWidth - 8
        sw.addTarget(self, action: #selector(switchChangeValue(sender:)), for: .valueChanged)
        sw.tag = 0
        return sw
    }()
    
    private lazy var tableView: UITableView = {
        let tab = UITableView(frame: CGRect(x: 0, y: naviView!.bottom, width: screenWidth, height: screenHeight - naviView!.bottom), style: .grouped)
        tab.backgroundColor = whiteColor
        tab.rowHeight = 50
        tab.delegate = self
        tab.dataSource = self
        tab.separatorStyle = .none
        tab.isScrollEnabled = false
        return tab
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func configView() {
        configNaviView(title: "SSID Settings")
        view.addSubview(tableView)
        
        rightBtn?.backgroundColor = clearColor
        rightBtn?.setTitle("OK", for: .normal)
        rightBtn?.setTitleColor(whiteColor, for: .normal)
        rightBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        
        getData()
    }
    
    override func rightBtnClicked(sender: UIButton) {
        let broadCast = nameSwitch.isOn ? "0" : "1"
        let cipher = values.last == "TKIP" ? "0" : (values.last == "AES" ? "1" : "2")
        var shared = "NONE"
        if values[2] == "WPA2-PSK/WPA2-PSK(TKIP)"  {
            shared = cipher
            values[2] = "WPAPSKWPA2PSK"
        }
        if  values[2] == "WPA2-PSK(AES)" {
            shared = cipher
            values[2] = "WPA2PSK"
        }
        net_setSSID(ssid: values[0], broadcast: broadCast, secureMode: values[2], pwd: values[3].base64String(), max: values[4], cipher: cipher, shared: shared) {[weak self] (success) in
            if success {
                self?.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    @objc private func switchChangeValue(sender:UISwitch) {
        values[1] = sender.isOn ? "0" : "1"
    }
    
    private func getData() {
        net_getDeviceInfoList {[weak self] (model) in
            if model != nil {
                self?.values[0] = model!.sSID1!
                self?.values[1] = model!.mHideSSID!
                
                if model!.authMode! == "WPAPSKWPA2PSK" {
                   self?.values[2] = "WPA2-PSK/WPA2-PSK(TKIP)"
                }else if model!.authMode! == "WPA2PSK" {
                    self?.values[2] = "WPA2-PSK(AES)"
                }else{
                    
                    self?.values[2] = model!.authMode!
                }
                
                self?.values[3] = String(data: Data(base64Encoded: model!.wPAPSK1Encode!)!, encoding: .utf8)!
                self?.values[4] = model!.mAXAccessNum!
                self?.nameSwitch.isOn = self?.values[1].caseInsensitiveCompare("1") == .orderedSame ? false : true
                self?.values.append(model!.encrypType!)
            }
            self?.tableView.reloadData()
        }
    }

}

extension SSIDSettingsVC : UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = datas[indexPath.row]
        cell.textLabel?.font = UIFont.systemFont(ofSize: 18)
        cell.textLabel?.textColor = textGray
        cell.selectionStyle = .none
        if indexPath.row != 1 {
            cell.accessoryType = .disclosureIndicator
        }else {
            cell.contentView.addSubview(nameSwitch)
        }
        
        
        if indexPath.row == 0 || indexPath.row == 3 {
            let attS = NSMutableAttributedString(string: cell.textLabel!.text!)
            attS.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.red], range: NSRange(location: attS.string.count - 1, length: 1))
            cell.textLabel?.attributedText = attS
        }
        
        if indexPath.row != 1 && indexPath.row != 3{
            let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
            if indexPath.row == 0 {
                label.width = 120
            }else if indexPath.row == 2 {
                label.width = 180
            }
            label.right = screenWidth - 40
            label.text = values[indexPath.row]
            label.font = cell.textLabel?.font
            label.textColor = cell.textLabel?.textColor
            label.backgroundColor = clearColor
            label.textAlignment = .right
            cell.contentView.addSubview(label)
        }
        
        if indexPath.row == 3 {
            let label = UITextField(frame: CGRect(x: 0, y: 0, width: 120, height: 50))
            label.right = screenWidth - 40
            label.text = values[indexPath.row]
            label.font = cell.textLabel?.font
            label.textColor = cell.textLabel?.textColor
            label.backgroundColor = clearColor
            label.textAlignment = .right
            label.isSecureTextEntry = true
            label.isUserInteractionEnabled = false
            cell.contentView.addSubview(label)
        }
        
        
        let line = UIView(frame: CGRect(x: 8, y: 50 - 0.5, width: screenWidth - 16, height: 0.5))
        line.backgroundColor = textGray
        cell.contentView.addSubview(line)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.row != 1 else {
            return
        }
        
        if indexPath.row == 0 || indexPath.row == 3{
            let alertView = InputAlertView(input: values[indexPath.row], isShowPassword: indexPath.row == 3)
            alertView.handle = ({[weak self] content in
                self?.values[indexPath.row] = content
                self?.tableView.reloadData()
            })
            let alertVC = CustomAlertVC(contentType: .animation(alertView))
            alertVC.show()
        }else {
            var numbers : [String] = []
            for i in 1..<11 {
                numbers.append("\(i)")
            }
            let pickerData : [String] = indexPath.row == 2 ?
                ["OPEN",
                "WPA2-PSK(AES)",
                "WPA2-PSK/WPA2-PSK(TKIP)"] : numbers
            
            
            let alertView = PickerAlertView(title: "Select", data: pickerData)
            alertView.handle = ({[weak self] index in
                self?.values[indexPath.row] = pickerData[index]
                self?.tableView.reloadData()
            })
            let alertVC = CustomAlertVC(contentType: .animation(alertView))
            alertVC.show()
        }
       
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
